package com.samehope.ar.controller;


import com.samehope.ar.common.CommonResult;
import com.samehope.ar.constant.IsManageEnum;
import com.samehope.ar.dto.CompanyAddParam;
import com.samehope.ar.dto.CompanyDefaultParam;
import com.samehope.ar.dto.CompanyUpdateParam;
import com.samehope.ar.entity.SysUserCompany;
import com.samehope.ar.service.ICompanyService;
import com.samehope.ar.service.ISysUserCompanyService;
import com.samehope.ar.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 * 公司 前端控制器
 * </p>
 *
 * @author Zhang Luo
 * @since 2019-12-23
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ISysUserCompanyService userCompanyService;

    /**
     * 新增企业, 并返回企业ID
     * @param param
     * @return
     */
    @PostMapping("/add")
    public CommonResult add(@RequestBody @Valid CompanyAddParam param) {
        return CommonResult.success(companyService.addCompany(param));
    }

    /**
     * 为用户设置默认企业
     * @param param
     * @return
     */
    @PutMapping("/setDefault")
    public CommonResult setDefault(@RequestBody @Valid CompanyDefaultParam param) {
        companyService.setDefault(param.getCompanyId());
        return CommonResult.success(null);
    }

    /**
     * 更新企业
     * @param param
     * @return
     */
    @PutMapping("/update")
    public CommonResult update(@RequestBody @Valid CompanyUpdateParam param){
        SysUserCompany userCompany = userCompanyService.findByCompanyAndUser(param.getCompanyId(), SessionUtil.getUserId());
        if (!IsManageEnum.YES.getCode().equals(userCompany.getIsManage())) {
            return CommonResult.unauthorized("没有相关权限");
        }
        companyService.update(param);
        return CommonResult.success(null);
    }

    /**
     * 删除企业
     * @param companyId
     * @return
     */
    @PreAuthorize("hasRole('ROLE_COMPANY')")
    @DeleteMapping("/del/{companyId}")
    public CommonResult del(@PathVariable("companyId") Long companyId){
        companyService.del(companyId);
        return CommonResult.success(null);
    }

    /**
     * 用户所属企业列表
     * @return
     */
    @GetMapping("list")
    public CommonResult list(){
        return CommonResult.success(companyService.findByUser());
    }

    @GetMapping("detail")
    public CommonResult detail(@RequestParam(required = true) Long companyId){
        return CommonResult.success(companyService.detail(companyId));
    }
}
